import React from 'react'

// 导入 TodoItem 类型
import { TodoItem } from '../todos'

// 提供 props 类型
interface Props {
  list: TodoItem[],
  onEditTodo(id: number, text: string): void,
  onDeleteTodo(id: number): void,
  onChangeDone(id: number): void,
  onChangeEdit(id: number): void,
}

interface State {
  text: string
}

class TodoList extends React.Component<Props, State> {
  state: State = {
    text: ''
  }

  onDoubleEdit = (todo: TodoItem) => {
    // 完成状态不可编辑
    if (todo.done) return
    // 存在正在编辑的任务不可编辑
    if (this.props.list.find(todo => todo.edit)) return
    // 显示编辑输入框和编辑内容
    this.props.onChangeEdit(todo.id)
    this.setState({ text: todo.text })
  }

  onEditChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      text: e.target.value
    })
  }

  // 编辑任务
  onEdit = (e: React.KeyboardEvent<HTMLInputElement>, id: number) => {
    // 1 非空判断
    const { text } = this.state
    if (text.trim() === '') return
    // 监听键盘事件 enter 键
    if (e.keyCode === 13 || e.code === 'Enter') {
      // console.log('enter')
      this.props.onEditTodo(id, text)
      // 2 清空文本框的值
      this.setState({ text: '' })
    }
  }

  render() {
    // console.log(this.props)
    return (
      <ul className="todo-list">
        {/* 编辑样式：editing  已完成样式：completed */}
        {this.props.list.map(todo => {
          return (
            <li
              key={todo.id}
              className={
                todo.done ? 'completed' :
                  todo.edit ? 'editing' : ''
              }
              // 双击编辑
              onDoubleClick={() => this.onDoubleEdit(todo)}
            >
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={todo.done}
                  onChange={() => { this.props.onChangeDone(todo.id) }}
                />
                <label>{todo.text}</label>
                <button
                  className="destroy"
                  onClick={() => this.props.onDeleteTodo(todo.id)}
                />
              </div>
              <input
                className="edit"
                autoFocus
                value={this.state.text}
                onChange={this.onEditChange}
                onKeyDown={(e) => this.onEdit(e, todo.id)}
              />
            </li>
          )
        })}
        {/* 无数据 */}
        {this.props.list.length === 0 &&
          (
            <li>
              <div className="view">
                <label>请添加待办事项！</label>
              </div>
            </li>
          )
        }
      </ul>
    )
  }
}

export default TodoList
